#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

//项目路径和工程id
const std::string pathname = "./Comm.hpp";
const int proj_id = 0x11223344;
//共享内存大小
const int size = 4096;
//管道文件名称
const std::string filename = "fifo_file";

//创建key值
key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if(key < 0)
    {
        std::cout << "ftok craet key fail" << std::endl;
        exit(1);
    }
    return key;
}

int ShmgetHelper(key_t key, int flag)
{
    int shmid = shmget(key, size, flag);
    if(shmid < 0)
    {
        std::cout << "shmget create system v shared memory fail" << std::endl;
        exit(2);
    }
    return shmid;
}

//创建共享内存
int CreateShm(key_t key)
{
    return ShmgetHelper(key, IPC_CREAT | IPC_EXCL | 0666);
}
//获取共享内存
int GetShm(key_t key)
{
    return ShmgetHelper(key, IPC_CREAT);
}
//创建管道文件
void Makefile()
{
    int n = mkfifo(filename.c_str(), 0666);
    if(n < 0)
    {
        //已经存在了
        if(errno == EEXIST)
            return;
        //真的出错了
        std::cout << "mkfifo create pipe file fail" << std::endl;
        exit(3);
    }
}
